package com.njtoyo.taxi.admin.service.data.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.handler.FilterHandler;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.Enum;
import com.njtoyo.taxi.admin.mapper.secondary.entity.cache.CacheCustomer;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.cache.CacheCustomerMapper;
import com.njtoyo.taxi.admin.rest.presenter.data.chart.RankChartItemPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.data.data_analysis.ChartWrapper;
import com.njtoyo.taxi.admin.service.data.CallCustomerService;
import com.taxi.entity.common.RestResult;
import com.njtoyo.taxi.entity.backend.AdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@DS(Const.SECONDARY_DS)
@Service
public class CallCustomerServiceImpl implements CallCustomerService {

    @Autowired
    private CacheCustomerMapper cacheCustomerMapper;

    @Override
    public RestResult<List<RankChartItemPresenter>> chart(AdminUser adminUser, ChartWrapper wrapper) {
        FilterHandler filterHandler = new FilterHandler(adminUser, wrapper.getCantonId(), wrapper.getCompanyId());
        QueryWrapper<CacheCustomer> queryWrapper = new QueryWrapper<>();
        if (wrapper.getGroupType().equals(Enum.DateGroupType.month)) {
            wrapper.setStartTime(DateUtil.beginOfMonth(wrapper.getStartTime()));
            wrapper.setEndTime(DateUtil.endOfMonth(wrapper.getEndTime()));
        }

        queryWrapper.ge("stats_date", DateUtil.format(wrapper.getStartTime(), DatePattern.NORM_DATE_PATTERN))
                .le("stats_date", DateUtil.format(wrapper.getEndTime(), DatePattern.NORM_DATE_PATTERN));
        switch (filterHandler.getFilterType()) {
            case canton:
            case company:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
        }
        List<CacheCustomer> customerList = cacheCustomerMapper.selectList(queryWrapper);
        List<RankChartItemPresenter> res = new ArrayList<>();
        if (wrapper.getGroupType().equals(Enum.DateGroupType.month)) {
            Map<String, List<CacheCustomer>> result = customerList.stream().collect(Collectors.groupingBy(i -> DateUtil.format(i.getStatsDate(), DatePattern.NORM_MONTH_PATTERN)));
            Date currentDate = wrapper.getStartTime();
            while (currentDate.before(wrapper.getEndTime())) {
                RankChartItemPresenter item = new RankChartItemPresenter();
                item.setStart(DateTime.of(currentDate));
                List<CacheCustomer> customer = result.get(DateUtil.format(currentDate, DatePattern.NORM_MONTH_PATTERN));
                Long count = 0L;
                if (CollectionUtil.isNotEmpty(customer)) {
                    List<Integer> allRes = new ArrayList<>();
                    for (CacheCustomer val: customer) {
                        List<Integer> cList = (List<Integer>) JSON.parse(val.getRealtimeCall());
                        allRes.addAll(cList);
                    }
                    allRes = new ArrayList<>(new LinkedHashSet<>(allRes));
                    count = (long) allRes.size();
                }

                // 翻倍率
                Double customerRate = filterHandler.getFakeMultiple().getActiveCustomer();
                if (Objects.nonNull(customerRate)) {
                    count = (long) (Long.parseLong(count.toString()) * customerRate);
                }
                item.setTotal(count);
                res.add(item);
                currentDate = DateUtil.offsetMonth(currentDate, 1);
            }
        } else {
            Map<String, List<CacheCustomer>> result = customerList.stream().collect(Collectors.groupingBy(i -> DateUtil.format(i.getStatsDate(), DatePattern.NORM_DATE_PATTERN)));
            Date currentDate = wrapper.getStartTime();
            while (currentDate.before(DateUtil.offsetDay(wrapper.getEndTime(), 1))) {
                RankChartItemPresenter item = new RankChartItemPresenter();
                item.setStart(DateTime.of(currentDate));
                List<CacheCustomer> customer = result.get(DateUtil.format(currentDate, DatePattern.NORM_DATE_PATTERN));
                Long count = 0L;
                if (CollectionUtil.isNotEmpty(customer)) {
                    List<Integer> allRes = new ArrayList<>();
                    for (CacheCustomer val: customer) {
                        List<Integer> cList = (List<Integer>) JSON.parse(val.getRealtimeCall());
                        allRes.addAll(cList);
                    }
                    allRes = new ArrayList<>(new LinkedHashSet<>(allRes));
                    count = (long) allRes.size();
                }

                // 翻倍率
                Double customerRate = filterHandler.getFakeMultiple().getActiveCustomer();
                if (Objects.nonNull(customerRate)) {
                    count = (long) (Long.parseLong(count.toString()) * customerRate);
                }
                item.setTotal(count);
                res.add(item);
                currentDate = DateUtil.offsetDay(currentDate, 1);
            }
        }

        return RestResult.success(res);
    }
}
